#include "precomp.h"
#include "mainwindow.h"
#include "encrypt_inc.h"

using namespace encrypt;

MainWindow::MainWindow(QWidget *parent)
    : QDialog(parent)
{
    QVBoxLayout *vertLayoutMain = new QVBoxLayout(this);
    vertLayoutMain->setContentsMargins(0, 0, 0, 0);

    QLabel *labelLogo = new QLabel(this);
    labelLogo->setScaledContents(true);
    labelLogo->setPixmap(QPixmap(":/keygen/image/bk-keygen.bmp"));
    vertLayoutMain->addWidget(labelLogo);

    QFormLayout *formLayout = new QFormLayout();
    formLayout->setContentsMargins(8, 0, 8, 0);
    vertLayoutMain->addLayout(formLayout);

    QLineEdit *lineEdit = new QLineEdit(this);
    lineEdit->setReadOnly(true);
    formLayout->addRow(QStringLiteral("Serial Number:"), lineEdit);

    QHBoxLayout *horiLayoutBottom = new QHBoxLayout();
    horiLayoutBottom->setContentsMargins(8, 8, 8, 8);
    vertLayoutMain->addLayout(horiLayoutBottom);

    QPushButton *buttonGenerate = new QPushButton(QStringLiteral("Generate"));
    QPushButton *buttonCopy = new QPushButton(QStringLiteral("Copy"));
    QPushButton *buttonExit = new QPushButton(QStringLiteral("Exit"));

    horiLayoutBottom->addStretch();
    horiLayoutBottom->addWidget(buttonGenerate);
    horiLayoutBottom->addWidget(buttonCopy);
    horiLayoutBottom->addWidget(buttonExit);

    //
    connect(buttonGenerate, &QPushButton::clicked, [=](){
        CSystemInfo systemInfo;

        CHAR strBIOSInfo[1024] = {0};
        systemInfo.m_biosInfo.GetBiosID(strBIOSInfo);

        //CHAR strCPUID[1024] = {0};
        //systemInfo.m_CPUID.GetFirstCPUID(strCPUID);

        CHAR strDiskSerial[1024] = {0};
        systemInfo.m_diskSerial.GetFirstDiskSerial(strDiskSerial);

        CHAR strMac[1024] = {0};
        systemInfo.m_ethernetMac.GetFirstMac(strMac);

        // Encrypt BIOS INFO + Disk Serial Number + Mac Address
        std::string input = std::string(strBIOSInfo) + std::string(strDiskSerial) + std::string(strMac);

        MD5 md5;
        md5.update(input);

        std::string output = md5.toString();

        //
        std::string output1;
        for (size_t i = 0; i < output.size() / 2; i++) {
            output1.append(1, output[i * 2 + 1]);
        }

        for (size_t i = 4; i < output1.size(); i+=5) {
            output1.insert(i, 1, '-');
        }

        lineEdit->setText(QString::fromStdString(output1));
    });
    connect(buttonCopy, &QPushButton::clicked, [=](){
        lineEdit->selectAll();
        lineEdit->copy();
    });
    connect(buttonExit, &QPushButton::clicked, [=](){
        this->accept();
    });
}
